package toy.keli.edic.ui.home

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.text.buildAnnotatedString
import toy.keli.edic.R
import toy.keli.edic.data.Db
import toy.keli.edic.data.GlobalVal
import toy.keli.edic.data.GlobalVal.clipboardManager
import toy.keli.edic.data.UserStatus
import toy.keli.edic.data.config.BookConf
import toy.keli.edic.data.config.MenuConf
import toy.keli.edic.data.config.PageConf
import toy.keli.edic.data.config.PathConf
import toy.keli.edic.data.file.Log
import toy.keli.edic.data.local.entity.DictionaryEntity
import toy.keli.edic.data.model.Article
import toy.keli.edic.data.model.Book
import toy.keli.edic.data.model.Query
import toy.keli.edic.data.model.WordExtend
import toy.keli.edic.domain.model.WordModel
import toy.keli.edic.ui.bookmark.BookMarkEvent
import toy.keli.edic.ui.bookmark.data.BookMark
import toy.keli.edic.ui.history.HistoryViewModel
import toy.keli.edic.ui.history.HistoryWords
import toy.keli.edic.ui.history.components.HistroyFilter
import toy.keli.edic.ui.home.components.AutoCompleteTextFieldEvent
import toy.keli.edic.ui.home.game.inputWord
import toy.keli.edic.ui.main.components.Display.mt
import toy.keli.edic.ui.main.components.InputDialog
import toy.keli.edic.ui.main.extend.MainMsg
import toy.keli.edic.ui.main.extend.MainRun
import toy.keli.edic.ui.main.extend.bgRun
import toy.keli.edic.ui.main.extend.stringRun
import toy.keli.edic.ui.navigation.NavScreen
import toy.keli.edic.util.ActivityRun
import toy.keli.edic.util.NetDicUtil
import toy.keli.edic.util.ScreenUtil
import toy.keli.edic.util.media.Audio
import toy.keli.edic.view.MPopMenu
import java.text.SimpleDateFormat
import java.util.Date

class HomeEvents {
    //状态或者说标志位
    object status  {
        var openDrowUp = true   //开启单指下拉功能
        var enableDrowUp = true   //下拉功能可用
        var enableDrowX = true   //左右滑动功能可用
        var enableDrowDown = false //上拉功能可用
        var openDrowX = false    //左右滑动功能开启

    }
    companion object {
        var downMenuOpen: Boolean by mutableStateOf(false)
        var showMainPage: (name:String) -> Unit ={}
        val events = Events()


        fun onback(abs:Boolean=false): Boolean {
            if(!events.onBackPressed()){
               return false
            }
//            if(viewMode!= MenuConf.mode.wordStudy){
//                viewMode = MenuConf.mode.wordStudy
//                return false
//            }
            if(downMenuOpen){
                downMenuOpen = false
                return false
            }
            //历史记录
            if(HistoryWords.size>1){
                HistoryWords.pop()
                return false
            }
            return true
            //底部菜单退出和现实方式退出
//            if(!abs && !events.onBackPressed()){
//                return
//            }
//            viewMode = when(viewMode){
//                MenuConf.mode.showBook ->MenuConf.mode.showBook //保持目录模式
//                MenuConf.mode.wordStudy -> MenuConf.mode.listenBook //单词模式到书本模式
//                MenuConf.mode.listenBook -> MenuConf.mode.showBook  //书本模式到目录模式
//                else->MenuConf.mode.wordStudy
//            }
//            when(nowBookShowType){
//                "word_shows" -> {
//                    val modeNow = MenuConf.modeNow()
//                    //历史记录
//                    if(!abs && viewMode == modeNow && HistoryWords.size>1){
//                        HistoryWords.pop()
//                        return
//                    }
//                    //其他模式返回主模式 或者返回列表
//                    if(viewMode != modeNow && false === PageConf.getBoolean(PageConf.homePage.RemainViewMode,true)){
//                        viewMode = modeNow
//                    }else {
//                        GroupInfoPage.beforMode = viewMode
//                        viewMode = MenuConf.mode.chapterPage
//                    }
//                }
//                "book_shows" -> {
//                    if(GroupInfoPage.beforMode!=null) {
//                        viewMode = GroupInfoPage.beforMode!!
//                    }else {
//                        MainRun(100) {
//                            val pid = Book.cid()
//                            BookMarkEvent.bookId = BookConf.instance.id
//                            NavScreen.BookmarkScreen.open("?pid=${pid}")
//                        }
//                    }
//                }
//                else -> {}
//            }
        }
        fun onNextWordBefore():Boolean{
            val modeNow = MenuConf.modeNow()
            //如果保持当前模式开启并且当前模式不等于默认模式则不进入下一个而是直接修改显示模式
            if(!PageConf.getBoolean(PageConf.homePage.RemainViewMode,true) && viewMode!= MenuConf.mode.chapterPage && viewMode!=modeNow){
                viewMode = modeNow
                return false
            }

            return true
        }
        fun onBackBefore(backfun:()->Boolean) {
            events.onBackPressed = backfun
        }

        fun onDownMenuShow(dfun:()->Unit) {
            events.onDownMenuShow = dfun
        }

        fun onDownMenuHide(dfun:()->Unit){
            events.onDownMenuHide = dfun
        }

        //水平滑动
        fun onDragHorizontal(x: Float) {
            //向右 上一个
            BookConf.instance.next(if(x>0) -1 else 1)
//            var pIndex = if(viewMode == MenuConf.mode.chapterPage) 0 else 1
//            pIndex += if(x>0) -1 else 1;
//            when(pIndex){
//                0-> onback(true)
//                1-> onback(true)
//                2-> NavScreen.BookmarkScreen.open()
//                else->{}
//            }
        }

        /**
         * 首页的点击事件 用于显示底部菜单和顶部路径与操作项目
         * 点击的位置
         */
        var timeOutClosedDownMenu = false;      //提供一个取消这个定时操作的方式
        fun onPanEnd(pos: Offset,value:Boolean?=null):Boolean {
            //如果是搜索打开模式就关闭搜索
            if(GlobalVal.isSearchVisible.value){
                GlobalVal.isSearchVisible.value = false;
                return true
            }
            return false
        }
        //首页显示菜单
        fun onOpenMenu(pos: Offset,value:Boolean?=null) {
            downMenuOpen = if(value==null) !downMenuOpen else value
            //获取系统标题状态确定是否需要显示系统标题
            val isHideSystemTitle = ! UserStatus.get{
                it.getBoolean("showSystemTitle",false)
            }
            if(isHideSystemTitle) {
                ScreenUtil.setFullScreen(ActivityRun.getAct(), !downMenuOpen)
            }
            if(downMenuOpen) {
                timeOutClosedDownMenu = true
                stringRun(9000) {
                    if(timeOutClosedDownMenu) {
                        timeOutClosedDownMenu = false
                        downMenuOpen = false;
                        events.onDownMenuHide()
                    }

                    if (isHideSystemTitle) {
                        MainRun {
                            ScreenUtil.setFullScreen(ActivityRun.getAct(), true)
                        }
                    }
                }
                events.onDownMenuShow()
            }else{
                events.onDownMenuHide()
            }
        }
        fun onBookShow(pid:Int,categoryId:Int=0,articleId:Int=0){
            downMenuOpen = false
            //不是选中直接打开
            if (categoryId + articleId == 0) {
                BookMark.changePid(pid)
            } else {
                BookMarkEvent.bookId = articleId
                BookMarkEvent.dirId = categoryId
                BookMark.changePid(pid)
            }

            SwitchMainPage.onItemClick(MenuConf.mode.showCategory)
        }
        fun onChangeViewModel(name:String="") {
            viewMode = when(name){
                "word" -> MenuConf.mode.wordStudy
                "book" -> MenuConf.mode.showArticle
                "category" -> MenuConf.mode.showCategory
                "" -> if(viewMode == MenuConf.mode.showCategory) MenuConf.mode.wordStudy else MenuConf.mode.showCategory
                else -> MenuConf.mode.wordStudy
            }
            SwitchMainPage.onItemClick(viewMode)
        }

        /**
         * 选择书本之前的操作
         * 实现 不依赖书本 可以从历史和字典中读取数据
         */
        fun onBeforeSelectBook(): Boolean {
            HistoryViewModel.getAll{
                //走历史
                if(it.size>0){
                    GlobalVal.wordModelList = it
                    BookConf.words = it
                    GlobalVal.wordViewModel.wordState.value = WordState(it.first())
                    GlobalVal.wordViewModel.detailState.value = true
                //走词典
                }else{
                    GlobalVal.wordViewModel.searcher("the", true)
                }
            }
            return false
        }

        class Events{
            var onDownMenuHide: () -> Unit ={}
            var onDownMenuShow: () -> Unit ={}
            var onBackPressed: () -> Boolean = {true}
        }
    }

    object SwitchMainPage {
        fun onItemClick(item: MenuConf.mode) {
            viewMode = item
            showMainPage(item.name)
            if(!GlobalVal.nav.equals(NavScreen.HomeScreen)) {
                NavScreen.openHome(0)
            }
            downMenuOpen = false;
        }
    }

    object GroupInfoPage {
        var beforMode: MenuConf.mode?=null
        var filterType:Int = -1
        var filterLevels:List<String> =listOf<String>()


        fun onWordClick(it: WordModel) {
            //设置单词重新刷新一下位置
            BookConf.instance.setWordByString(it.word)
            GlobalVal.wordViewModel.upList(BookConf.words)
            HistoryWords.reset()
            showMainPage(it.word)
//            if(beforMode!=null) {
//                viewMode = beforMode!!
//            }else{
//                viewMode = MenuConf.mode.wordStudy
//            }
        }

        fun onChapterClick(it: String) {
            nowChapters = it
            GlobalVal.bookmarkViewModel.changeChapter(it)
            if(filterType>-1 || filterLevels.size>0){
                bgRun {
                    Book.filter(filterType, filterLevels)
                }
            }
        }

        /**
         * 排除
         */
        fun onAddDiffSetClick() {

        }

        /**
         * 排除项的单击
         */
        fun onDiffSetItemClick() {
            TODO("Not yet implemented")
        }

        /**
         * 包含项目添加
         */
        fun onAddInSetClick() {
        }

        /**
         * 排除项目单击
         */
        fun onInSetItemClick() {
            TODO("Not yet implemented")
        }

        fun onFunsClick(menu: MPopMenu) {
            menu.show { k, v ->
                when (v.name) {
                    "Save" -> {
                        InputDialog.show(text = Book.words())
                    }
                    "SaveAll" -> {
                        InputDialog.show(text = Book.words(true))
                    }

                    "过滤" -> {
                        HistroyFilter.eventChange{type,date,levels,key->
                            filterType = type
                            filterLevels = levels
                            bgRun {
                                Book.filter(type, levels)
                            }
                        }
                        HistroyFilter.show()
                    }

                    "Copy" -> {
                        val words = BookConf.words.map { it.word }.joinToString(",")
                        clipboardManager.setText(buildAnnotatedString {
                            append(words)
                        })
                        ActivityRun.msg(mt("Copied"))
                    }

                    else -> {
                        val dateNow = Date(System.currentTimeMillis())
                        val date = SimpleDateFormat("yyyy-MM-dd_HH.mm.ss").format(dateNow)
                        val file = PathConf.dcim + BookConf.instance.name + "_" + date + ".jpg"
                        HistoryViewModel.printWordModelsToImg(BookConf.words, file)
                        ActivityRun.msg(mt("export") + file)
                        when (v.name) {
                            "exportAndJumpTo" -> {
                                ActivityRun.openFile(file)
                            }

                            "exportAndOpen" -> {
                                ActivityRun.openImg(file)
                            }
                        }
                    }
                }
            }
        }

        fun onHistoryWordClick(it: WordModel) {
            AutoCompleteTextFieldEvent.setSearchKey(it.word)
        }

        fun onBookClick(entity: toy.keli.edic.data.local.entity.ArticleEntity) {}
    }

    object scapesGame{
        lateinit var lastFindWordMode:WordModel
        /**
         * 单词找到事件
         */
        fun onFindWord(wm: WordModel?) {
            if(wm==null) return
            lastFindWordMode = wm
            if(wm.isStudyed) {
                return
            }
            ActivityRun.runOnUiThread {
                if(wm.ch!=null) {
                    ActivityRun.msg(wm.ch!!)
                }

                Audio.play(R.raw.correct)
                GlobalVal.tts.speak(wm.word)
            }
        }

        /**
         * 圆盘输入字母键入事件
         */
        fun onInPoint(c: Char, nowWord: String, wordFindOk: Boolean) {
            inputWord.value += c
            Audio.play(R.raw.p7)
        }

        /**
         * 圆盘输入结束事件
         */
        fun onInOver(nowWord: String) {
              inputWord.value = ""
        }
    }

    object exGame{
        //单词的单击事件
        fun onWordClick(wm: WordModel) {
            GlobalVal.tts.speak(wm.word)
        }

    }

    /**
     * 搜索
     */
    object searchTools{
        var defaultText=""
        var searchType=""
        fun show(word: String="",from:String="searchButton") {
            GlobalVal.isSearchVisible.value = true
            defaultText = word
            searchType = from;
        }
        /**
         * 匹配到词条
         */
        fun onPreMatcheMathchOk(query: String, onMatch: (word: String) -> Boolean): ArrayList<String>? {
            val setSug = onMatch(query)
            if(setSug) {
                val moreSug = arrayListOf<String>()
                val hQuery = Query(Db.user, "historyTable").like("word", query+"%%").limit(1000).build()
                moreSug.addAll(
                    Db.user.wordModelDao.getHistoryList(hQuery).map {
                        val date = SimpleDateFormat("MM月dd日HH点").format(Date(it.time))
                        var ch = if(it.ch!=null) it.ch?.take(4) else ""
                        "${it.word}:${ch}(${date})"
                    }.sorted()
                )

//            val queryObj = Query(Db.user, "historyTable").like("word", query).build()
//            moreSug.addAll(
//                Db.user.wordModelDao.getHistoryList(queryObj).map {
//                    val date = SimpleDateFormat("yyyy-MM-dd HH.mm").format(Date(it.time))
//                    "history:${date}"
//                }
//            )

                val bQuery = Query(Db.user, "bookmarkTable").like("word", query).build()
                moreSug.addAll(
                    Db.user.wordModelDao.getBookMarkList(bQuery).map {
                        val date = SimpleDateFormat("yyyy-MM-dd HH.mm").format(Date(it.intime))
                        "bookmark:${date}"
                    })
                //添加包含单词
                Article.getWords(
                    WordExtend(query).inword.filter {
                        query.indexOf(it)>-1
                    }
                ).filter{
                    it.level>0
                }.map{
                    var ch = (if(it.ch!=null) it.ch?.take(10) else "")
                    moreSug.add(it.word+":"+ch)
                };
//                                    moreSug.addAll(Article.grep(query).map { "article.${it.id}:${it.name}" })
//                                    moreSug.addAll(sublist)
                return moreSug
            }
            return null
        }

        /**
         * 为空的时候处理
         */
        fun onSuggestEmpty(query: String, onMatch: (word: String) -> Boolean): List<String>? {
            val reg = "(ing|ed|s)$"
            //适配语音输入
            if(query.startsWith(" ") || query.endsWith(".") || query.first().isUpperCase()) {
                val word = query.trim().trim('.').toLowerCase();
                GlobalVal.wordViewModel.prefixMatcher(word,true,onMatch=onMatch);
            }else if(query.matches(Regex(".+$reg"))){
                val word = query.replace(Regex(reg),"")
                GlobalVal.wordViewModel.prefixMatcher(word,true,onMatch=onMatch);
            }else{
                return WordExtend(query).getSameWords()
            }
            return null
        }

        /**
         * 仍然找不到尝试网络搜索
         */
        fun searchByOnline(word: String) {
            NetDicUtil.youdaoGet(word){
                val meanings = getMeanings()
                val ch = getCh()
                if(ch?.length==0 && meanings.equals("[]")){
                    Log.searchWordErr(word)
                    MainMsg("网络搜索失败！请确定单词拼写是否错误！")
                    return@youdaoGet
                }
                val w = DictionaryEntity(meanings, word, "tmpByNet:" + word, ch, 0)
                GlobalVal.wordViewModel.wordState.value = WordState(w.toWordModel())
                GlobalVal.wordViewModel.detailState.value = true;
                Log.searchWordLost(word)
            }
        }
    }
}